<template>
    <div id="abc">
        <home-head></home-head>
    </div>
    <div class="header-class-main-box">
        <div class="tab-container">
            <div class="tab" :class="{ active: activeTab === 'bookshelf' }" @click="activeTab = 'bookshelf'">我的书架</div>
            <div class="tab" :class="{ active: activeTab === 'history' }" @click="activeTab = 'history'">最近阅读</div>
        </div>

        <el-table v-if="activeTab === 'bookshelf'" :data="bookshelfData" border style="width: 100%" class="book-list" ref="bookshelfTableRef">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="category" label="分类"></el-table-column>
            <el-table-column prop="name" label="作品名" >
                <template #default="scope">
                    <div @click="goToDetail(scope.row.bookId)" style="cursor: pointer; color: #409eff;">
                        {{ scope.row.name }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="author" label="作者"></el-table-column>
            <el-table-column prop="latestChapter" label="最新章节"></el-table-column>
            <el-table-column prop="updateTime" label="更新时间"></el-table-column>
            <el-table-column prop="chapterName" label="最近阅读章节">
                <template #default="scope">
                    <router-link style="cursor: pointer; color: #409eff;"
                                 :to="`/chapter/${scope.row.bookId}/${scope.row.id}`">{{ scope.row.chapterName }}</router-link>
                </template>
            </el-table-column>
            <el-table-column prop="readTime" label="最近阅读时间"></el-table-column>
            <el-table-column prop="progress" label="阅读进度"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="handleBookshelfDelete([scope.row.id])" type="danger" size="large" style="color:#000000;background-color: #409eff">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-table v-else-if="activeTab === 'history'" :data="historyData" border style="width: 100%" class="book-list" ref="historyTableRef">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="category" label="分类"></el-table-column>
            <el-table-column prop="name" label="作品名" >
                <template #default="scope">
                    <div @click="goToDetail(scope.row.bookId)" style="cursor: pointer; color: #409eff;">
                        {{ scope.row.name }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="author" label="作者"></el-table-column>
            <el-table-column prop="latestChapter" label="最新章节"></el-table-column>
            <el-table-column prop="updateTime" label="更新时间"></el-table-column>
            <el-table-column prop="chapterName" label="最近阅读章节">
                <template #default="scope">
                    <router-link style="cursor: pointer; color: #409eff;"
                                 :to="`/chapter/${scope.row.bookId}/${scope.row.id}`">{{ scope.row.chapterName }}</router-link>
                </template>
            </el-table-column>
            <el-table-column prop="readTime" label="最近阅读时间"></el-table-column>
            <el-table-column prop="progress" label="阅读进度"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="handleHistoryDelete([scope.row.id])" type="danger" size="large" style="color:#000000;background-color: #409eff">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="batch-operations">
            <el-button v-if="activeTab === 'bookshelf'" @click="handleBatchBookshelfDelete" type="danger" class="btn">批量删除</el-button>
            <el-button v-if="activeTab === 'history'" @click="handleBatchHistoryDelete" type="danger" class="btn">批量删除记录</el-button>
        </div>
    </div>
    <home-bottom></home-bottom>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import HomeHead from "@/components/home/home-head.vue";
import request from '@/utils/request.js';
import router from "@/router/index.js";


const activeTab = ref('bookshelf');
const bookshelfTableRef = ref(null); // 书架表格引用
const historyTableRef = ref(null);   // 历史记录表格引用

const bookshelfData = ref([]);
const historyData = ref([
    {
        category: '都市激战',
        name: '女总裁的全能兵王',
        latestChapter: 'V·第6524章 人间炼狱',
        readTime: '2025-07-31 10:00:00',
        author: '寂寞的舞者',
        progress: '有更新',
        id: 1
    },
    {
        category: '玄幻奇幻',
        name: '万族之劫',
        latestChapter: '第1234章 新的时代',
        readTime: '2025-07-31 09:30:00',
        author: '老鹰吃小鸡',
        progress: '已读完',
        id: 2
    }
]);

// 获取书架数据
const fetchBookshelfData = async () => {
    try {
        const response = await request.get('/api/users/getbookshelf');
        bookshelfData.value = response.data;
    } catch (error) {
        ElMessage.error('获取书架数据失败');
    }
};

// 获取最近阅读数据
const fetchHistoryData = async () => {
    try {
        const response = await request.get('/api/users/reading-history');
        historyData.value = response.data;
    } catch (error) {
        ElMessage.error('获取最近阅读数据失败');
    }
};

// 组件挂载时获取数据
onMounted(() => {
    fetchBookshelfData();
    fetchHistoryData();
});

// 书架单个删除
const handleBookshelfDelete = async (ids) => {
    try {
        await ElMessageBox.confirm(
            `此操作将删除${ids.length > 1 ? '选中的' : '该'}书籍, 是否继续?`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        await request.post('/api/users/bookshelf/delete', { ids });

        // 前端移除数据
        bookshelfData.value = bookshelfData.value.filter(item => !ids.includes(item.id));

        // 清除选中状态
        if (bookshelfTableRef.value) {
            bookshelfTableRef.value.clearSelection();
        }

        ElMessage.success(`${ids.length > 1 ? '批量' : ''}删除成功!`);
    } catch (error) {
        handleDeleteError(error, ids.length > 1);
    }
};

// 书架批量删除
const handleBatchBookshelfDelete = async () => {
    const selectedRows = bookshelfTableRef.value ? bookshelfTableRef.value.getSelectionRows() : [];

    if (selectedRows.length === 0) {
        ElMessage.warning('请选择要删除的书籍');
        return;
    }

    const ids = selectedRows.map(item => item.id);
    handleBookshelfDelete(ids);
};

// 阅读记录单个删除
const handleHistoryDelete = async (ids) => {
    try {
        await ElMessageBox.confirm(
            `此操作将删除${ids.length > 1 ? '选中的' : '该'}阅读记录, 是否继续?`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        // 调用阅读记录删除接口
        await request.post('/api/users/reading-history/delete',  ids );

        // 前端移除数据
        historyData.value = historyData.value.filter(item => !ids.includes(item.id));

        // 清除选中状态
        if (historyTableRef.value) {
            historyTableRef.value.clearSelection();
        }

        ElMessage.success(`${ids.length > 1 ? '批量' : ''}删除记录成功!`);
    } catch (error) {
        handleDeleteError(error, ids.length > 1, true);
    }
};

// 阅读记录批量删除
const handleBatchHistoryDelete = async () => {
    const selectedRows = historyTableRef.value ? historyTableRef.value.getSelectionRows() : [];

    if (selectedRows.length === 0) {
        ElMessage.warning('请选择要删除的阅读记录');
        return;
    }

    const ids = selectedRows.map(item => item.id);
    handleHistoryDelete(ids);
};

// 统一处理删除错误
const handleDeleteError = (error, isBatch, isHistory = false) => {
    if (error === 'cancel' || error.name === 'CanceledError') {
        ElMessage.info('已取消删除');
    } else {
        const typeText = isHistory ? '阅读记录' : '书籍';
        ElMessage.error(`${isBatch ? '批量' : ''}删除${typeText}失败`);
    }
};
const goToDetail = (id) => {
    router.push({
        name: 'bookList', // 对应路由配置中的name
        params: { id } // 传递id参数
    });
};
</script>

<style scoped>

.header-class-main-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    max-width: 1200px;
    margin: 20px auto;
    gap: 20px;
    box-shadow:
        0 2px 8px rgba(135, 206, 235, 0.3),  /* 下方阴影 */
        0 -2px 8px rgba(135, 206, 235, 0.3), /* 上方阴影 */
        2px 0 8px rgba(135, 206, 235, 0.3),  /* 右侧阴影 */
        -2px 0 8px rgba(135, 206, 235, 0.3); /* 左侧阴影 */
}

.tab-container {
    display: flex;
    border-bottom: 2px solid #ccc;
    margin-bottom: 20px;
}

.tab {
    padding: 10px 20px;
    cursor: pointer;
    font-size: 18px;
    margin-right: 10px;
    border-bottom: 2px solid transparent;
    transition: all 0.3s ease;
}

.tab.active {
    color: #00b9ff;
    border-bottom: 2px solid #00b9ff;
}

.tab:hover {
    color: #00b9ff;
}

.btn {
    margin-top: 20px;
    color:#000000;
    background-color: #409eff;
}

.batch-operations {
    align-self: flex-start;
    margin-left: 0;
}

.delete-btn {
    background-color: #00b9ff;
}

.delete-btn:hover {
    background-color: #00b9ff;
}

.no-data {
    text-align: center;
    padding: 20px;
    color: #999;
}
</style>
